package com.ygxsk.carhome.ui.property;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.listener.DoubleClickListener;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.response.CategoryAddBottomBean;
import com.ygxsk.carhome.response.CategoryAddTopBean;
import com.ygxsk.carhome.response.PropertyRepairTransBean;
import com.ygxsk.carhome.response.PropertyRepairTransOutsideBean;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.adapter.PropertyRepairTransAdapter;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.integrated.retrofit.Parameterkey;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi175@163.com
 * @Time:2023/12/27  13:36
 * @Description:物业报修二期版本添加, 直接就是报修项分类,一级分类
 */
public class PropertyRepairTransActivity extends ErrorActivity implements ErrorParentExtraSingle {

    @BindView(R.id.refreshLayoutpropertyrepairtrans)
    SmartRefreshLayout refreshLayoutPropertyRepairTrans;

    @BindView(R.id.recyclerviewinpropertyrepairtrans)
    RecyclerView recyclerViewInPropertyRepairTrans;


    //该列表的适配器内容
    private PropertyRepairTransAdapter propertyRepairTransAdapter;

    private ArrayList<PropertyRepairTransBean> mDatasResources = new ArrayList<>();
    //携带维修空间，外侧，需要携带到提交报修列表
    private ArrayList<CategoryAddBottomBean> spaceList_outSide = new ArrayList<>();

    /**
     * 跳转界面的标识，从哪个界面回转过来还是从哪个界面跳转过来的
     * 目前这个界面的话，这个标识仅仅用作是否是从物业缴费缴费成功的【物业报修】跳转过来
     * 如果是，那么就回退到首页2018/11/30
     */
    private int jumpFromFlag;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        if (mDatasResources == null) {
            mDatasResources = new ArrayList<>();
        }

        if (spaceList_outSide == null) {
            spaceList_outSide = new ArrayList<>();
        }

        processExtraData();

        initloading();

        initViews();

        gainDatas();

        //暂时用不到
        /*if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }*/

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_property_repair_trans;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();

    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

//        toolbarHelper.setLayoutSao(false, null);
        //选择报修类别的时候跳转到该界面
        toolbarHelper.setTitle(getString(R.string.title_choose_repair_type));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());

        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                methodBack();

            }
        });

        toolbarHelper.setLayoutClose(false, "", null);

        //貌似整个项目只有这个特殊：物业报修的右侧按钮特殊 使用第二种风格的按钮。
        toolbarHelper.setLayoutRight(true, 1, getResources().getString(R.string.title_my_reapir), new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                // TODO: 2023/12/27 15:08  跳转到我的报修记录
                ActivityUtils.startActivity(PropertyRepairActivity.class);

            }
        });

    }

    @Override
    protected void onClickNodata(View v) {

        gainDatas();

    }

    @Override
    protected void initViews() {

        recyclerViewInPropertyRepairTrans.setLayoutManager(new LinearLayoutManager(this));
        propertyRepairTransAdapter = new PropertyRepairTransAdapter(R.layout.pertyrepairtransadapter, mDatasResources);
        recyclerViewInPropertyRepairTrans.setAdapter(propertyRepairTransAdapter);
        propertyRepairTransAdapter.notifyDataSetChanged();

        propertyRepairTransAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                //该条数据
                PropertyRepairTransBean propertyRepairTransBean = (PropertyRepairTransBean) adapter.getItem(position);

                if (propertyRepairTransBean != null) {

                    //携带维修位置：
                    ArrayList<CategoryAddTopBean> childRepairTypeList = propertyRepairTransBean.getChildRepairTypeList();

                    if (!DoubleClickListener.isFastDoubleClick()) {

                        Bundle bundle = new Bundle();

                        bundle.putString(ExtraKey.EXTRA_REPAIRTYPEID, mDatasResources.get(position).getRepairTypeId());

                        // TODO: 2023/12/28 14:15 新项目和红色物业不同的，因为要携带维修位置和维修空间。
                        bundle.putParcelableArrayList(ExtraKey.EXTRA_CHILDREPAIRTYPELIST, childRepairTypeList);

                        // TODO: 2023/12/28 14:20 新项目和红色物业不同，携带维修位置过去
                        bundle.putParcelableArrayList(ExtraKey.EXTRA_SPACELIST, spaceList_outSide);

                        // TODO: 2023/12/27 15:06 跳转到提交页面,和红色物业有不同
                        ActivityUtils.startActivity(bundle, RepairAddSubmitActivity.class);

                    }

                }

            }
        });

        refreshLayoutPropertyRepairTrans.setEnableLoadMore(false);

        refreshLayoutPropertyRepairTrans.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

                        gainDatas();

                        refreshLayout.finishRefresh();

                    }
                });

            }
        });

    }

    @Override
    protected void gainDatas() {

        if (NetworkUtils.isConnected()) {

//            repairIdPass = null;
            if (mDatasResources != null && !mDatasResources.isEmpty()) {
                mDatasResources.clear();
            }

            if (propertyRepairTransAdapter != null) {
                propertyRepairTransAdapter.notifyDataSetChanged();
            }

//            getServerDatas(repairIdPass);
            getServerDatas();

        } else {

            netWorkError();

            //setEnableLoadmore(refreshLayoutPropertyRepairtrans, false);

        }

    }

    private void getServerDatas() {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());//,

//        map.put(Parameterkey.status, "0");//状态
//        map.put(Parameterkey.status, RepairStatusUpLoadType.STATE_PENDING_HANDLER.getIndex());//状态

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETONESTAIRVILLAGEREPAIRTYPE_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getOneStairVillageRepairType_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(false);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getOneStairVillageRepairType(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(PropertyRepairTransActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<PropertyRepairTransOutsideBean>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        methodNotSuccessData(what_method, serverCode, serverMessage);

                        //{"data":"","message":"无更多数据","code":"29999"}
//                        {"data":"","message":"无数据","code":"20002"}

                        //这里要不要给提示？无更多数据
//                        if (!TextUtils.equals(serverCode, ConstantSign.RESPONSE_20002)) {

                        //无数据这个就不提示了，因为筛选条件很多，一会一提示 不友好；
                        if (!TextUtils.isEmpty(serverMessage)) {
                            ToastUtils.showShort(serverMessage);
                        }

//                            if (mDatasResources != null && mDatasResources.isEmpty()) {
//
//                                CommUtils.checkCurrently((ErrorActivity) mActivityInstance,//
//                                        serverCode,//
//                                        R.drawable.errorsear,//
//                                        serverMessage,//
//                                        getString(R.string.nulldatanow));
//
//                            }

//                        } else {
//                            LogUtils.d(ConstantSign.LOGCAT_NOMAL + getString(R.string.donot_show_toast));
//                        }

                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {

                        loadingGone();
//                        setEnableLoadmore(refreshLayoutPropertyRepairTrans, true);

                    }
                }).subscribe(new Consumer<PropertyRepairTransOutsideBean>() {
                    @Override
                    public void accept(PropertyRepairTransOutsideBean propertyRepairTransOutsideBean) throws Throwable {

                        if (propertyRepairTransOutsideBean != null) {

//                            ArrayList<RepairManageItemBean> currentDatas = repairManageItemOutSide.getDataList();

//                            if (currentDatas != null && !currentDatas.isEmpty()) {
//                                if (mDatasResources != null) {
//                                    mDatasResources.addAll(currentDatas);
//                                }
//                            }

                            ArrayList<PropertyRepairTransBean> repairTypeList = propertyRepairTransOutsideBean.getRepairTypeList();

                            if (repairTypeList != null && !repairTypeList.isEmpty()) {

                                if (mDatasResources != null) {
                                    mDatasResources.addAll(repairTypeList);
                                }

                            }

                        } else {
                            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "propertyRepairTransOutsideBean 是空的");
                        }

                        //这里也不用管是下拉刷新或者上拉加载更多，直接判断是否为空，
                        if (mDatasResources != null && mDatasResources.isEmpty()) {
//                            setEnableLoadmore(refreshLayoutPropertyRepairTrans, false);
                            fillNullDataView(StringUtils.getString(R.string.nulldatanow), R.drawable.errorsear);
                        }

                        if (propertyRepairTransAdapter != null) {
                            propertyRepairTransAdapter.notifyDataSetChanged();
                        }

                        //---------------------------------------------------------------------------------------------------------
                        //携带维修物品空间的列表。
                        ArrayList<CategoryAddBottomBean> spaceList = propertyRepairTransOutsideBean.getSpaceList();

                        if (spaceList != null && !spaceList.isEmpty()) {
                            if (spaceList_outSide != null) {
                                spaceList_outSide.addAll(spaceList);
                            }
                        }

                        //---------------------------------------------------------------------------------------------------------
                        //给分页值
//                        pagination_upLoad = repairManageItemOutSide.getNextPagination();
                        //对列表改造：
//                        if (pagination_upLoad == Parameterkey.GET_NEXT_PAGINATION) {
//                            setFinishLoadMoreWithNoMoreData(refreshLayoutPropertyRepairTrans, true);
//                        } else {
//                            setEnableLoadmore(refreshLayoutPropertyRepairTrans, true);
//                        }

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        //页面报错；
                        if (apiException != null) {
                            ToastUtils.showShort(apiException.getDisplayMessage());
                        }

                    }
                });

    }

    @Override
    public void methodNotSuccessData(int what_method, String serverCode, String serverMessage) {
        super.methodNotSuccessData(what_method, serverCode, serverMessage);

        switch (what_method) {

            case ConstantApi.WHAT_GETONESTAIRVILLAGEREPAIRTYPE_URL: {

                if (mDatasResources != null && mDatasResources.isEmpty()) {

                    CommUtils.checkCurrently((ErrorActivity) mActivityInstance,//
                            serverCode,//
                            R.drawable.errorsear,//
                            serverMessage,//
                            getString(R.string.nulldatanow));
                }

                break;
            }

            default:
                break;
        }

    }

    @Override
    protected void methodBack() {
        methodBackFinish();
    }

    @Override
    public void processExtraData() {

        Bundle bundle = this.getIntent().getExtras();

        if (bundle != null) {
            jumpFromFlag = bundle.getInt(ExtraKey.EXTRA_JUMPFROM_WHERE);
        }

    }
}